import logging, sys
import time
import grpc
from luoding_src.proto import detect_pb2
from luoding_src.proto import detect_pb2_grpc
import cv2
import numpy as np

def mat2bytes(image: np.ndarray) -> bytes:
    return np.array(cv2.imencode('.jpg', image)[1]).tobytes()

def bytes2mat(image: bytes) -> np.ndarray:
    return cv2.imdecode(np.array(bytearray(image), dtype='uint8'), cv2.IMREAD_UNCHANGED)

def read_bytes_img(frame: str) -> bytes:
    ''' frame Into bytes '''
    # 图像编码
    # print(f'frame:{frame}')
    success, img_encoded = cv2.imencode('.jpg', frame)
    # 图像转换为bytes
    img_encoded_bytes = img_encoded.tobytes()
    return img_encoded_bytes


def stream_video(img, channel_n_port):
    with grpc.insecure_channel(channel_n_port) as channel:
        stub = detect_pb2_grpc.DetectServiceStub(channel)
        img = cv2.resize(img, (640, 400))
        img_bytes = mat2bytes(img)
        requests = detect_pb2.FrameRequest(origin_frame=img_bytes)

        try:
            response = stub.streamVideo(requests)
            # print(response)
            # logging.info('response flag' + response)
        except:
            print('response error!')
            logging.info('response error!')

if __name__ == '__main__':
    img = cv2.imread('F:\dataset_yimu\luoding_test/Image_20231018141420717.jpg')
    print(img.shape)
    stream_video(img, 'localhost:6667')
